<template>
  <div class="page-container">
    <div class="card-container with-header">
      <div class="card-header">
        <div class="header-title">位置列表</div>
      </div>
      
      <!-- 搜索和操作区域 -->
      <div class="action-bar">
        <div class="search-area">
          <el-form :inline="true" :model="queryParams" @keyup.enter="handleSearch">
            <el-form-item>
              <el-select v-model="queryParams.typeId" placeholder="选择位置类型" clearable>
                <el-option
                  v-for="item in typeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="queryParams.keyword"
                placeholder="请输入位置名称或地址"
                clearable
                style="width: 220px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="action-btns">
          <el-button type="primary" @click="handleAdd">新增位置</el-button>
        </div>
      </div>
      
      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="locationList" border style="width: 100%">
        <el-table-column type="index" width="50" align="center" label="序号" />
        <el-table-column prop="name" label="位置名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="address" label="位置地址" min-width="200" show-overflow-tooltip />
        <el-table-column label="位置类型" min-width="100" align="center">
          <template #default="scope">
            <el-tag>{{ scope.row.locationType?.name || '未知' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="坐标" min-width="180" align="center">
          <template #default="scope">
            {{ scope.row.latitude }}, {{ scope.row.longitude }}
          </template>
        </el-table-column>
        <el-table-column prop="viewCount" label="查看次数" width="100" align="center" />
        <el-table-column label="推荐" width="80" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.isRecommend"
              :active-value="1"
              :inactive-value="0"
              @change="handleRecommendChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getLocationList, getLocationTypeList, deleteLocation, setRecommendStatus } from '@/api/location'

const router = useRouter()

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  typeId: undefined,
  keyword: ''
})

// 数据相关
const loading = ref(false)
const locationList = ref([])
const total = ref(0)
const typeOptions = ref([])

// 查询位置列表
const getList = () => {
  loading.value = true
  getLocationList(queryParams)
    .then(res => {
      locationList.value = res.data.records
      total.value = res.data.total
    })
    .catch(error => {
      console.error('获取位置列表失败:', error)
      ElMessage.error('获取位置列表失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 获取位置类型选项
const getTypeOptions = () => {
  getLocationTypeList()
    .then(res => {
      typeOptions.value = res.data
    })
    .catch(error => {
      console.error('获取位置类型失败:', error)
    })
}

// 搜索
const handleSearch = () => {
  queryParams.current = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.typeId = undefined
  queryParams.keyword = ''
  handleSearch()
}

// 新增位置
const handleAdd = () => {
  router.push('/location/add')
}

// 编辑位置
const handleEdit = (row) => {
  router.push(`/location/edit/${row.id}`)
}

// 删除位置
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除位置 ${row.name} 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteLocation(row.id).then(() => {
      ElMessage.success('删除成功')
      getList()
    }).catch(error => {
      console.error('删除位置失败:', error)
      ElMessage.error('删除位置失败')
    })
  }).catch(() => {})
}

// 修改推荐状态
const handleRecommendChange = (row) => {
  const status = row.isRecommend
  const statusText = status === 1 ? '推荐' : '取消推荐'
  
  setRecommendStatus(row.id, status)
    .then(() => {
      ElMessage.success(`${statusText}成功`)
    })
    .catch(error => {
      console.error(`${statusText}失败:`, error)
      ElMessage.error(`${statusText}失败`)
      // 还原状态
      row.isRecommend = status === 1 ? 0 : 1
    })
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.size = val
  getList()
}

// 当前页改变
const handleCurrentChange = (val) => {
  queryParams.current = val
  getList()
}

// 初始化
onMounted(() => {
  getTypeOptions()
  getList()
})
</script>

<style lang="scss" scoped>
.action-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 